// +----------------------------------------------------------------------
// | 补助单业务目录
// getExpenseInfo();            step01:获取出差报销单数据
// getApplyList();              step02:获取出差申请单列表
// travelOrderOpen();           step03:打开订单列表
// showOrder();                 step04:显示订单
// addListenOrderChooseIds();   step05:发送监听事件
// getTripPolicyInfo();         step06:获取我的差旅政策
// getPassengerList();          step07:获取审批人数据，公司全部员工删除但不包含登录人
// picker1Select();          step07:获取审批人数据，公司全部员工删除但不包含登录人
// +----------------------------------------------------------------------
(function (window) {
    'use strict';
    var allowanceAdd = function (params) {
        this.extend(this.params, params);
        this._init();
    };

    var toast = new auiToast();

    allowanceAdd.prototype = {
        //参数
        params : {
            oneMaxAmount    : ''  //todo
            ,twoMaxAmount   : ''  //todo
            ,otherMaxAmount : ''  //todo
            ,allowance_rule : ''  //出差补助
            ,data1          : []  //出行人数据
            ,data2          : []  //审批人数据
            ,applyOrder     : ''  //1开启申请单0关闭申请单
            ,ids            : []
        }

        //初始化
        ,_init : function () {
            var that = this;
            //step1:获取申请单是否开启
            that.getExpenseInfo();                  //step01:获取出差报销单数据
            //公用
            that.showOrder();                       //step04:关闭申请单情况下显示订单
            that.getTripPolicyInfo();               //step06:获取差旅政策
            that.getPassengerList();                //step07:获取审批人数据，公司全部员工删除但不包含登录人
            that.picker1Select();                   //step08:选择出行人
            that.delTravelPersonAddEvent();         //step09:删除人员
            that.submitData();                      //step10:提交出差补助单
            that.autoCalculate();                   //step11:补助标准输入失去焦点时自动计算
            that.dateClick();                       //step12:使用mobisroll日期插件
            //工具
            that.extend();                          //tool_01:函数:扩展
        }


        //step01:获取出差报销单数据
        ,getExpenseInfo : function () {
            var that = this;

            var param = {};
            param.url = Config.common.getCompanyInfo;
            //请求申请单列表接口
            ajax(param, function(ret) {
                //整合参数
                var tempApply = {
                    applyOrder : ret.apply_order
                };
                that.extend(that.params, tempApply);
                if (ret.apply_order === 1) {
                    //开启申请单操作
                    that.getApplyList();                //step02:获取出差申请单列表
                } else {
                    //关闭申请单操作
                    that.travelOrderOpen();             //step03:打开订单列表
                    that.addListenOrderChooseIds();     //step05:发送监听事件
                }
            })
        }

        //step02:获取出差申请单列表
        ,getApplyList : function () {
            var that = this;

            var data2 = that.params.data2;
            var param = {};
            param.url = Config.travel.mineApplyListAllowance;
            param.data = {};
            /*请求申请单列表接口*/
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    that.createList2(ret.data.data, data2);
                    that.picker2Select();
                } else {
                    toast.custom({
                        title: ret.msg,
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            });
        }

        //step03:打开订单列表
        ,travelOrderOpen: function () {
            $("#picker2").click(function() {
                api.openWin({
                    name: 'travel_order_choose_win',
                    url: './travel_order_choose_win.html'
                });
            });
            $("#picker2").children('.aui-list-item-title').text('请选择差旅订单');
        }

        //step04:显示订单
        ,showOrder :function () {
            $('body').on('click', '.show_order', function() {
                //折叠
                $('.order_' + $(this).attr('data-group')).toggle();
                //文字显示
                var i = $(this).text();
                if (i === '展开') {
                    $(this).empty().text('收回');
                } else if(i === '收回'){
                    $(this).empty().text('展开');
                }
            });
        }

        //step05:发送监听事件
        ,addListenOrderChooseIds: function () {
            var that = this;

            api.addEventListener({
                name: 'order_choose_ids'
            }, function(ret, err) {
                that.getOrderList(2, ret.value.orderids);
            });
        }

        //step06:获取我的差旅政策
        ,getTripPolicyInfo : function () {
            var that = this;

            var param = {};
            var oneMaxAmount = 0;
            var twoMaxAmount = 0;
            var otherMaxAmount = 0;
            var allowance_rule = 0;
            param.url = Config.common.myTripPolicy;
            // console.log(param);
            //请求申请单列表接口
            ajax(param, function(ret) {
                // console.log(ret);
                if (ret.code === 1) {
                    //step1:获取基本数据
                    $("#allowance_standard").val(ret.data.trip_allowance);  //补助金额（可以变量）
                    $("#default_standard").text(ret.data.trip_allowance);   //补助金额（固定不变）
                    $("#hotel_standard").val(ret.data.hotel_policy.oneMaxAmount);   //一级城市X元/间夜
                    //step2：转换为小数
                    allowance_rule = parseFloat(ret.data.allowance_rule);   //出行截止日
                    oneMaxAmount = parseFloat(ret.data.hotel_policy.oneMaxAmount); //一级城市
                    twoMaxAmount = parseFloat(ret.data.hotel_policy.twoMaxAmount); //二级城市X元/间夜
                    otherMaxAmount = parseFloat(ret.data.hotel_policy.otherMaxAmount); //其他级城市X元/间夜

                    //step3:整合为参数
                    var tempAmount = {
                        oneMaxAmount : oneMaxAmount,
                        twoMaxAmount : twoMaxAmount,
                        otherMaxAmount : otherMaxAmount,
                        allowance_rule : allowance_rule
                    };
                    that.extend(that.params, tempAmount);
                } else {
                    toast.custom({
                        title : ret.msg, //获取我的差旅政策失败
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            })
        }

        //step07:获取审批人数据，公司全部员工删除但不包含登录人
        ,getPassengerList : function () {
            var that = this;

            var data1 = that.params.data1;
            var param = {};
            param.url = Config.travel.getPassengerList;
            //获取出差/审核人员接口
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    //审批人中删除当前登录人
                    delete ret.data[$api.getStorage('user_id')];
                    that.createList(ret.data, data1);
                } else {
                    toast.custom({
                        title: "获取审批人失败",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            })
        }

        //step08:选择出行人
        ,picker1Select : function () {
            var that = this;

            var data1 = that.params.data1;
            var picker1El = document.getElementById('picker1');  //审核人 选择器
            var picker1 = new Picker({
                data: [data1]
            });
            //选择后调用
            picker1.on('picker.select', function(selectedVal, selectedIndex) {
              if ($.inArray(selectedVal.toString(),that.params.ids) != -1) {
                $alert(data1[selectedIndex[0]].text+'  已经存在，请重新选择');
                return false;
              }
                //选择审核人
                var interText = doT.template($("#person_tpl").text());
                $(".expense_person").append(interText({
                    'text': data1[selectedIndex[0]].text,
                    'val': selectedVal
                }));
                that.params.ids.push(selectedVal.toString());
                // data1.splice(selectedIndex[0], 1);
            });
            //添加触发
            picker1El.addEventListener('click', function() {
                picker1.show(function() {
                    picker1.refill([data1]);
                });
            });
        }

        //step09:删除人员
        , delTravelPersonAddEvent: function () {
            var that = this;
            var data1 = that.params.data1;
            $('body').on('click', '.delete_person', function () {
                var temp = [];
                temp.value = $(this).parent().attr('data-val');
                temp.text = $(this).parent().find('.u_name').text();
                // data1.push(temp);
                that.params.ids.splice($.inArray(temp.value,that.params.ids),1);
                $(this).parent().remove();
            });
        }

        //step10:提交出差补助单
        ,submitData: function () {
            var that = this;
            //点击提交的操作
            $('#submitData').click(function () {
                //验证器
                if (!that.validateData()) {
                    return false;
                }
                //订单IDS
                var order_ids = '';
                $("#order_list ul").each(function() {
                    order_ids += $(this).attr('data-id') + ',';
                });
                order_ids = order_ids.substr(0, order_ids.length - 1);

                //报销明细
                var detail;
                var detailArr = [];
                $(".detail_price").each(function() {
                    var temp = [];
                    temp.hotel_standard = $(this).find('.hotel_standard').text();
                    temp.real_fee = $(this).next().find('.real_fee').text();
                    temp.number_of_days = $(this).next().next().find('.number_of_days').text();
                    detailArr.push(temp);
                });
                if (detailArr.length > 0) {
                    detail = detailArr;
                }
                //审批人
                var approver = '';
                $(".expense_person li").each(function() {
                    approver += $(this).attr('data-val') + ',';
                });
                approver = approver.substr(0, approver.length - 1);

                var param = {};
                param.url = Config.travel.addAllowance;
                param.data = {
                    detail: detail,
                    request_code: $("#picker2 span").text(),
                    approve_ids: approver,
                    order_ids: order_ids,
                    travel_start_time: $("#my-startDate").val(),
                    travel_end_time: $("#my-endDate").val(),
                    travel_allowance: $("#allowance_price").text(),
                    economy_sum: $("#save_price").text(),
                    total_money: $("#total_price").text(),

                    day_of_travel: $("#days_sum").val(),
                    allowance_standard: $("#allowance_standard").val(),
                    hotel_standard: $("#hotel_standard").val()
                };
                ajax(param, function(ret) {
                    // console.log(ret);
                    if (ret.code === 1) {
                        toast.custom({
                            title: "申请成功",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                        api.openWin({
                            name: 'travel_allowance_order_win',
                            url: './travel_allowance_order_win.html'
                        });
                    } else {
                        toast.custom({
                            title: "申请失败",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                    }
                })
            });
        }

        //step11:补助标准输入失去焦点时自动计算
        ,autoCalculate : function () {
            var that = this;
            //step1:补助标准自动计算
            $("input[name='allowance_standard']").focus(function () {
                that.calculatePrice();
            });
            $("input[name='allowance_standard']").blur(function () {
                that.calculatePrice();
            });
            //step2:出差天数自动计算
            $("input[name='days_sum']").focus(function () {
                that.calculatePrice();
            });
            $("input[name='days_sum']").blur(function () {
                that.calculatePrice();
            });
        }

        //step12:使用mobisroll日期插件
        ,dateClick: function () {
            var that = this;
            $('#my-startDate').mobiscroll().date({
                theme: 'mobiscroll',
                lang: 'zh',
                dateFormat: 'yyyy-mm-dd',
                display: 'center',
                mode: 'Basic usage date'
            });
            $('#my-endDate').mobiscroll().date({
                theme: 'mobiscroll',
                lang: 'zh',
                dateFormat: 'yyyy-mm-dd',
                display: 'center',
                mode: 'Basic usage date'
            });
        }

        //step13:获取订单列表
        ,getOrderList : function (type, ids) {
            var that = this;
            var param = {};
            param.url = Config.travel.getApplyOrderListAllowance;
            param.data = {
                type: type,
                ids: ids,
                limit: 20
            };
            //请求申请单列表接口
            ajax(param, function(ret) {
                // console.log(ret);
                if (ret.code === 1) {
                    if (ret.data.plane.total > 0 || ret.data.hotel.total > 0 || ret.data.train.total > 0) {
                        var interText = doT.template($("#order_tpl").text());
                        //清空
                        $("#order_list").text('');
                        //机票
                        if (ret.data.plane.total > 0) {
                            var htmlPlane = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlPlane += '<div class="aui-info-item"><span class="aui-margin-l-5">机票订单</span></div>';
                            htmlPlane += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlPlane);
                            $("#order_list").append(interText(ret.data.plane.data));
                        }
                        //酒店
                        if (ret.data.hotel.total > 0) {
                            var htmlHotel = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlHotel += '<div class="aui-info-item"><span class="aui-margin-l-5">酒店订单</span></div>';
                            htmlHotel += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlHotel);
                            $("#order_list").append(interText(ret.data.hotel.data));
                        }
                        //车票
                        if (ret.data.train.total > 0) {
                            var htmlTrain = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlTrain += '<div class="aui-info-item"><span class="aui-margin-l-5">车票订单</span></div>';
                            htmlTrain += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlTrain);
                            $("#order_list").append(interText(ret.data.train.data));
                        }//清空
                        $("#order_list").text('');
                        //机票
                        if (ret.data.plane.total > 0) {
                            var htmlPlane = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlPlane += '<div class="aui-info-item"><span class="aui-margin-l-5">机票订单</span></div>';
                            htmlPlane += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlPlane);
                            $("#order_list").append(interText(ret.data.plane.data));
                        }
                        //酒店
                        if (ret.data.hotel.total > 0) {
                            var htmlHotel = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlHotel += '<div class="aui-info-item"><span class="aui-margin-l-5">酒店订单</span></div>';
                            htmlHotel += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="hotel">展开</span></div></div>';
                            $("#order_list").append(htmlHotel);
                            $("#order_list").append(interText(ret.data.hotel.data));
                        }
                        //车票
                        if (ret.data.train.total > 0) {
                            var htmlTrain = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlTrain += '<div class="aui-info-item"><span class="aui-margin-l-5">车票订单</span></div>';
                            htmlTrain += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="train">展开</span></div></div>';
                            $("#order_list").append(htmlTrain);
                            $("#order_list").append(interText(ret.data.train.data));
                        }
                        //补助明细
                        var interText2 = doT.template($("#allowance_tpl").text());
                        var j = 0;
                        for (var i = 0; i < ret.data.hotel.data.length; i++) {
                            if (ret.data.hotel.data[i]['is_to_yourself'] === 1) {
                                ret.data.hotel.data[i]['prop'] = ++j;
                                ret.data.hotel.data[i]['hotel_standard'] = that.getHotelStandard(ret.data.hotel.data[i]);
                                $("#days_sum").parent().parent().parent().after(interText2(ret.data.hotel.data[i]));
                            }
                        }
                        //统计日期
                        that.calculateDate();
                        that.calculatePrice();
                    } else {
                        toast.custom({
                            title: "您的申请单没有相关行程或未开始",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                    }
                } else {
                    toast.custom({
                        title: "获取订单失败",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            })
        }

        //step14:对比获取酒店标准
        ,getHotelStandard : function (order_info) {
            var that = this;

            var oneLevelCity = that.params.oneLevelCity;
            var twoLevelCity = that.params.twoLevelCity;

            var hotel_standard = 0;
            if (hotel_standard === 0) {
                for (var i = 0; i < oneLevelCity.length; i++) {
                    if (oneLevelCity[i].indexOf(order_info['city']) !== -1 || order_info['city'].indexOf(oneLevelCity[i]) !== -1) {
                        hotel_standard = that.params.oneMaxAmount;
                        break;
                    }
                }
            }
            if (hotel_standard === 0) {
                for (var j = 0; j < twoLevelCity.length; i++) {
                    if (twoLevelCity[j].indexOf(order_info['city']) !== -1 || order_info['city'].indexOf(twoLevelCity[j]) !== -1) {
                        hotel_standard = that.params.twoMaxAmount;
                        break;
                    }
                }
            }
            if (hotel_standard === 0) {
                hotel_standard = that.params.otherMaxAmount;
            }

            return hotel_standard;
        }

        //step15:选择审批人
        , picker2Select : function () {
            var that = this;
            let data2 = that.params.data2;
            //step1:更改名称
            $("#picker2").children('.aui-list-item-title').text('请选择出差申请单');
            //step2:点击事件
            var picker2El = document.getElementById('picker2');
            var picker2 = new Picker({
                data: [data2]
            });
            //选择后调用
            picker2.on('picker.select', function(selectedVal, selectedIndex) {
                $("#order_list").text('');
                $("#picker2").find('span').text(data2[selectedIndex[0]].text);
                that.getOrderList(1, data2[selectedIndex[0]].text);
            });
            //添加触发
            picker2El.addEventListener('click', function() {
                if (data2.length > 0) {
                    picker2.show();
                } else {
                    toast.custom({
                        title: "还没有申请单",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            });
        }

        //step16:计算日期
        , calculateDate : function () {
            var that = this;

            var start_time = '';
            var end_time = '';
            $("#order_list input[name='travel_start_time']").each(function() {
                if (start_time === '') {
                    start_time = $(this).val();
                } else {
                    if (start_time > $(this).val() && $(this).val() !== '') {
                        start_time = $(this).val();
                    }
                }
            });
            $("#order_list input[name='travel_end_time']").each(function() {
                if (end_time === '') {
                    end_time = $(this).val();
                } else {
                    if (end_time < $(this).val() && $(this).val() !== '') {
                        end_time = $(this).val();
                    }
                }
            });
            //第1个日期
            var date1 = new Date(start_time * 1000);
            var Y1 = date1.getFullYear() + '-';
            var M1 = (date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1) + '-';
            var D1 = date1.getDate();
            //第2个日期
            var date2 = new Date(end_time * 1000);
            var Y2 = date2.getFullYear() + '-';
            var M2 = (date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1) + '-';
            var D2 = date2.getDate();

            $("#my-startDate").val(Y1 + M1 + D1);
            $("#my-endDate").val(Y2 + M2 + D2);

            var dateTime = 1000 * 60 * 60 * 24; //每一天的毫秒数
            var minusDays = Math.floor(((date2 - date1) / dateTime)); //计算出两个日期的天数差
            var days = Math.abs(minusDays); //取绝对值
            //出差天数
            days += that.params.allowance_rule;

            $("#days_sum").val(days);
        }

        //step17:计算总金额
        , calculatePrice : function () {
            //step1:补助总额
            var day_sum = $("#days_sum").val() !== '' ? parseFloat($("#days_sum").val()) : 0;
            var standard_price = $("#allowance_standard").val() !== '' ? $("#allowance_standard").val() : 0;
            var allowance_price = day_sum * standard_price;
            $("#allowance_price").text(allowance_price);

            //step2:节约归己
            var detail_price = 0;
            var hotel_standard = parseFloat($("#hotel_standard").val());
            if ($(".detail_price").length > 0) {
                $(".detail_price").each(function() {
                    var real_fee = parseFloat($(this).next().find(".real_fee").text());
                    var number_of_days = parseFloat($(this).next().next().find('.number_of_days').text());
                    if (!real_fee && !hotel_standard ) {
                        if (hotel_standard > real_fee) {
                            detail_price += (hotel_standard - real_fee) * number_of_days;
                        }
                    }
                });
            }
            $("#save_price").text(detail_price.toFixed(2));

            //step3:补助总额
            var total_price = 0;
            total_price = (allowance_price + detail_price).toFixed(2);
            $("#total_price").text(total_price);
        }

        //step18:验证数据
        ,validateData : function () {
            //关联订单
            if ($("#order_list ul").length === 0) {
                toast.custom({
                    title: "请关联订单",
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                return false;
            }
            //明细
            //补助标准
            if ($("#allowance_standard").val() === 0) {
                toast.custom({
                    title: "请填写补助标准",
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                return false;
            }
            //天数
            if ($("#days_sum").val() === 0) {
                toast.custom({
                    title: "请填写出差天数",
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                return false;
            }
            //审批人
            if ($(".expense_person li").length === 0) {
                toast.custom({
                    title: "请选择审批人",
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                return false;
            }
            return true;
        }

        //step19:更改日期
        ,changeDate: function () {
            var that = this;

            //点击开始日期和结束日期触发的事件
            $('#my-startDate,  #my-endDate').change(function () {
                var start_time = $("#my-startDate").val();
                var end_time = $("#my-endDate").val();

                if (start_time !== '' && end_time !== '') {
                    start_time = new Date(start_time.replace(/-/g, "/"));
                    end_time = new Date(end_time.replace(/-/g, "/"));
                    var minusDays = end_time.getTime() - start_time.getTime();
                    var days = parseFloat(minusDays / (1000 * 60 * 60 * 24));
                    days = Math.abs(days);
                    //出差天数
                    days += that.params.allowance_rule;
                    $("#days_sum").val(days);
                    that.calculatePrice();
                }
            });
        }

        //tool_01:函数:扩展
        , extend: function (a, b) {
            for (var key in b) {
                if (b.hasOwnProperty(key)) {
                    a[key] = b[key];
                }
            }
            return a;
        }

        //tool_02:picker 底部选择器数据结构生成
        ,createList : function (obj, list) {
            var arr = Object.keys(obj);
            for (var i = 0; i < arr.length; i++) {
                var k = arr[i];
                var temp = [];
                temp.text = obj[k].user_name;
                temp.value = obj[k].user_id;
                list.push(temp);
            }
        }

        //tool_03:picker 底部选择器数据结构生成2
        , createList2 : function (obj, list) {
            var arr = Object.keys(obj);
            for (var i = 0; i < arr.length; i++) {
                var k = arr[i];
                var temp = [];
                temp.text = obj[k].travel_application_number;
                temp.value = obj[k].id;
                list.push(temp);
            }
        }
    };

    window.allowanceAdd = allowanceAdd;
})(window);
